package org.vergil.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.vergil.messagelistener.UserMessageListener;

/**
 * Created by vergil on 5/1/17.
 */
@Configuration
public class MqConfig {

    @Bean
    public SingleConnectionFactory connectionFactory(){
        return new SingleConnectionFactory(targetConnectionFactory());
    }

    @Bean
    public PooledConnectionFactory pooledConnectionFactory(){
        PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory();
        pooledConnectionFactory.setConnectionFactory(targetConnectionFactory());
        pooledConnectionFactory.setMaxConnections(10);
        return pooledConnectionFactory;
    }
    //真正可以产生Connection的ConnectionFactory，由对应的 JMS服务厂商提供
    @Bean
    public ActiveMQConnectionFactory targetConnectionFactory(){
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
        activeMQConnectionFactory.setBrokerURL("tcp://localhost:61616");
        return activeMQConnectionFactory;
    }

    /**
     * Spring提供的JMS工具类，它可以进行消息发送、接收等
     * @return
     */
    @Bean
    public JmsTemplate jmsTemplate(){
        return new JmsTemplate(pooledConnectionFactory());
    }

    /**
     * 这个是队列目的地，点对点的
     * @return
     */
    @Bean
    public ActiveMQQueue queueDestination(){
        return new ActiveMQQueue("devTest");
    }

    @Bean
    public ActiveMQTopic topicDestination(){
        return new ActiveMQTopic("topic");
    }

    @Bean
    public UserMessageListener userMessageListener(){
        return new UserMessageListener();
    }

    /**
     * 消息监听容器
     * @return
     */
    @Bean
    public DefaultMessageListenerContainer jmsContainer(){
        DefaultMessageListenerContainer defaultMessageListenerContainer =
                new DefaultMessageListenerContainer();
        defaultMessageListenerContainer.setConnectionFactory(pooledConnectionFactory());
        defaultMessageListenerContainer.setDestination(queueDestination());
        defaultMessageListenerContainer.setMessageListener(userMessageListener());
        return defaultMessageListenerContainer;
    }
}
